<?php

declare(strict_types=1);

namespace app\common\service\hrm;

use app\common\traits\ServiceTrait;
use app\common\dao\hrm\DeptDao;
use app\common\service\sys\UserService;
use app\common\util\TreeUtil;
use app\common\traits\TreeServiceTrait;

/**
 * 部门 -- 业务
 * @author:kaige
 * @update:2022-06-17
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 */
class DeptService
{
  protected $dao = null;

  public function __construct()
  {
    $this->dao = new DeptDao();
  }
  use ServiceTrait, TreeServiceTrait;

  /**
   * 重写with
   */
  public function _list_with()
  {
    return ['glcompany'];
  }

  /**
   * 重写 表格过滤条件
   * @param $post
   * @return array
   */
  public function _list_where($post)
  {
    $where = [];
    if (isset($post['company_id']) && !empty($post['company_id'])) {
      $where[] = ['company_id', '=', $post['company_id']];
    }
    if (isset($post['status']) && $post['status'] != "") {
      $where[] = ['status', '=', $post['status']];
    }
    if (isset($post['keywords']) && !empty($post['keywords'])) {
      $where[] = ['name|code', 'like', '%' . $post['keywords'] . '%'];
    }
    $result['where'] = $where;
    $result['field'] = ["*,pid as parentId"];
    $result['order'] = ['sort' => 'asc', 'id' => 'desc'];
    return $result;
  }
  /**
   * 重写 根据查询结果，格式化数据
   * @param $list
   * @return mixed
   */
  public function _list_format($list)
  {
    foreach ($list as $k => $v) {
      if (isset($v['pid'])) {
        $list[$k]['pobj'] = $this->getPid($v['pid']);
      }
      if (isset($v['glcompany'])) {
        unset($v['glcompany']);
      }
    }
    return $list;
  }

  /**
   * 根据Id获取部门名称
   */
  public static function getNameById($id)
  {
    return (new DeptDao())->getNameById($id);
  }

  /**
   * 获取部门列表
   * @return array
   */
  public static function getDeptList()
  {
    return (new DeptDao())->getListAll(['status' => 1], ['sort' => 'asc']);
  }


  /**
   * 获取所有列表树型
   * @return array
   */
  public function getDeptTree()
  {
    $data = $this->dao->getListAll(true, ['sort' => 'asc']);
    return $this->createTree($data, 0);
  }

  /**
   * 把数组构建成一维的有缩进的树
   * @param $list
   * @param int $pid
   * @return array
   */
  public function createTree($list, $pid = 0, $level = 1)
  {
    $data = [];
    $str = "";
    for ($i = 0; $i < $level; $i++) {
      if ($i > 0) $str .= ' ';
    }
    if ($level == 1) {
      $str .= '';
    } else {
      $str .= ' ';
    }
    foreach ($list as $k => $v) {
      if ($v["pid"] == $pid) {
        $v['name'] = $str . $v['name'];
        $data[] = $v;
        $ch = $this->createTree($list, $v['id'], $level + 1);
        $data = array_merge($data, $ch);
      }
    }
    return $data;
  }

  /**
   * 获取所有部门数组-(id,pid,name,sort)
   * @return array
   */
  public function getDeptArray()
  {
    $data = $this->dao->getListAll(true, ['sort' => 'asc'], ['id,pid,name,sort']);
    return $data;
  }

  /**
   * 获取部门数组，加入all元素
   * @return array
   */
  public function getDeptArray2()
  {
    $all = ['id' => 'all', 'name' => '全部', 'pid' => 0, 'sort' => 0];
    $data  = $this->getDeptArray();
    array_unshift($data, $all);
    return $data;
  }

  /**
   * 获取父部门
   * @param pid
   * @return object
   */
  public function getPid($pid)
  {
    $parentinfo = $this->dao->getInfoById($pid);
    return $parentinfo;
  }

  /**
   * 递归取得所有的父节点
   */
  public function getPids($id)
  {
    $data = [];
    $info = $this->dao->getInfoById($id);
    if (!$info) {
      return $data;
    }
    $info = object_array($info);
    //判断是否还有父节点，如果有，就取父节点，如果没有，就返回了
    if ($info['pid'] != 0) {
      $data = $this->getPids($info['pid']); //返回空数组或者二维数组
    }
    array_push($data, $info);
    return $data;
  }

  /**
   * 获取树型
   */
  public function deptTree()
  {
    $tree = [];
    $list = $this->dao->getListAll(['status' => 1], ['sort' => 'asc'], ['name,id as value,id,pid']);
    if ($list) {
      foreach ($list as $k => $v) {
        $list[$k]['isShow'] = true;
      }
      $tree = TreeUtil::list_to_tree($list, 0, 'id', 'pid', 'children');
    }
    return $tree;
  }

  /**
   * 获取部门-用户树形 -API用
   */
  public function getDeptTreeUseAPI()
  {
    $list =  $this->dao->getListAll(['status' => 1], ['sort' => 'asc'], ['id,pid,name,sort,extend']);
    if ($list) {
      //取出部门人员
      $us = new UserService();
      foreach ($list as $k => $v) {
        $list[$k]['type'] = 'department';
        $list[$k]['isShow'] = 1;
        $ul = $us->getDeptUserList($v['id']);
        if ($ul) {
          foreach ($ul as $k1 => $v1) {
            $ul[$k1]['type'] = 'user';
            $ul[$k1]['isShow'] = 1;
            if (isset($v1['avatar'])) {
              $ul[$k1]['avatar'] = _img($v1['avatar']);
            }
          }
          $list[$k]['children'] = $ul;
        }
      }
      //树型
      $list = TreeUtil::list_to_tree($list, 0, 'id', 'pid', 'children');
    }
    return $list;
  }

  /**
   * 获取部门-用户树形 -选择用户时用
   */
  public function getDeptLayuiTree()
  {
    $list =  $this->dao->getListAll(['status' => 1], ['sort' => 'asc'], ['id,pid,name as title,sort,extend as spread']);
    if ($list) {
      //取出部门人员
      $us = new UserService();
      foreach ($list as $k => $v) {
        $ul = $us->getDeptUserList($v['id']);
        if ($ul) {
          foreach ($ul as $k1 => $v1) {
            if (isset($v1['avatar'])) {
              $ul[$k1]['avatar'] = _img($v1['avatar']);
            }
          }
          $list[$k]['list'] = $ul;
        }
      }
    }
    //树型
    $list = TreeUtil::list_to_tree($list, 0, 'id', 'pid', 'children');
    return $list;
  }

  /**
   * 获取部门-用户 后台Szim用
   */
  public function getDeptUseSzim()
  {
    $list =  $this->dao->getListAll([['status', '=', 1], ['pid', '>', 0]], ['sort' => 'asc'], ['id,name as title,1 as spread']);
    if ($list) {
      $us = new UserService();
      //取出部门人员
      foreach ($list as $k => $v) {
        $ul = $us->getDeptUserList($v['id']);
        if ($ul) {
          foreach ($ul as $k1 => $v1) {
            if (isset($v1['avatar'])) {
              $ul[$k1]['avatar'] = _img($v1['avatar']);
            }
            $ul[$k1]['chat_type'] = 1; //聊天类型
          }
          $list[$k]['children'] = $ul;
        } else {
          unset($list[$k]);
        }
      }
    }
    return $list;
  }

  /**
   * 列出所有子节点
   * @param int $id
   * @param bool $noid 是否包含本身
   * @return string '1,2,3..'
   */
  public function inSubs($id, $noid = false)
  {
    $arr = '';
    if (!empty($id)) {
      $data = $this->getsubid($id);
      foreach ($data as $k => $v) {
        $arr .= $v['id'] . ',';
      }
      if ($noid)
        $arr .= $id;
    }
    $arr = rtrim($arr, ",");
    return $arr;
  }

  /**
   * 递归无限级分类【先序遍历算】，获取任意节点下所有子孩子
   * @param array $arrCate 待排序的数组
   * @param int $pid 父级节点
   * @param int $level 层级数
   * @return array $arrTree 排序后的数组
   */
  function deptSon($arrCat, $pid = 0, $level = 0)
  {
    static  $arrTree = array(); //使用static代替global
    if (empty($arrCat)) return FALSE;
    $level++;
    foreach ($arrCat as $key => $value) {
      if ($value['pid'] == $pid) {
        $value['level'] = $level;
        $arrTree[] = $value;
        unset($arrCat[$key]); //注销当前节点数据，减少已无用的遍历
        $this->deptSon($arrCat, $value['id'], $level);
      }
    }
    return $arrTree;
  }

  //找子节点
  public function getsubid($id)
  {
    $data = [];
    $d1 = $this->getListAll(['id' => $id]); //找出当前部门所有数据
    if (!$d1) {
      return $data;
    }
    $data = $this->deptSon($d1, $id, 0);
    return $data;
  }
}
